<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\FangRequest;
use App\Models\City;
use App\Models\Fang;
use App\Models\Fangattr;
use App\Models\FangOwner;
use Illuminate\Http\Request;

// 导入ES生成索引
use Elasticsearch\ClientBuilder;

class FangController extends BaseController
{
    /**
     * 房源列表显示
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        // 关联关系的调用
        $data = Fang::with(['owner'])->paginate($this->pagesize);
        // $data = $data['data'];
        // (new Fang())->location('重庆市江北区南桥苑19号楼', '重庆市');
        return view('admin.fang.index', compact('data'));
    }

    /**
     *
     */
    public function create()
    {
        $data = (new Fang())->relationData();
        // 返回数据
        return view('admin.fang.create', compact('data'));
    }

    /**
     * @param FangRequest $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(FangRequest $request)
    {
        $data  = $request->except(['_token', 'file']);
        $model = Fang::create($data);
        // 调用方法获取经纬度
        $locationArr = (new Fang())->location($model->fang_addr, $model->fang_city);
        if ($locationArr != []) {
            // 获取成功则更新数据入库
            $model->update([
                'longitude' => $locationArr[0],
                'latitude'  => $locationArr[1]
            ]);
        }
        // 数据创建成功后 es数据的添加
        // 得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        $params = [
            'index' => 'fang',
            'type'  => '_doc',
            'id'    => $model->id,
            'body'  => [
                'fang_name' => $model->fang_name,
                'fang_desn' => $model->fang_desn,
            ],
        ];
        $client->index($params);

        return redirect(route('admin.fang.index'));
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Models\Fang $fang
     * @return \Illuminate\Http\Response
     */
    public function show(Fang $fang)
    {
        //
    }

    /**
     * @param Fang $fang
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Fang $fang)
    {
        $cities  = City::where('pid', $fang->fang_province)->get();
        $regions = City::where('pid', $fang->fang_city)->get();
        $data    = (new Fang())->relationData();
        return view('admin/fang/edit', compact('fang', 'data', 'cities', 'regions'));
    }

    /**
     * @param FangRequest $request
     * @param Fang $fang
     * @return array
     */
    public function update(FangRequest $request, Fang $fang)
    {
        // 接受表单数据
        $data = $request->except('_token', 'file');
        // 数据修改入库
        $fang->update($data);
        // 经纬度修改
        $locationArr = (new Fang())->location($fang->fang_addr, $fang->fang_city);
        if ($locationArr != []) {
            // 获取成功则更新数据入库
            $fang->update([
                'longitude' => $locationArr[0],
                'latitude'  => $locationArr[1]
            ]);
        }
        // 数据创建成功后 es数据的更新
        // 得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        $params = [
            'index' => 'fang',
            'type'  => '_doc',
            // id 存在则修改
            'id'    => $fang->id,
            'body'  => [
                'fang_name' => $fang->fang_name,
                'fang_desn' => $fang->fang_desn,
            ],
        ];
        $client->index($params);
        return ['status' => 200, 'msg' => '更新成功'];
    }

    /**
     * @param Fang $fang
     * @return array
     * @throws \Exception
     */
    public function destroy(Fang $fang)
    {
        $fang->delete();
        return ['status' => 200, 'msg' => '删除成功'];
    }

    // upimg
    public function upimg(Request $request)
    {
        $pic = config('uploadpic.img');
        if ($request->hasFile('file')) {
            $info = $request->file('file')->store('', 'fangattr');
            $pic  = '/uploads/fangattr/images/' . $info;
        }
        return ['code' => 200, 'src' => $pic];
    }

    //delimg
    public function delimg(Request $request)
    {
        $filepath = $request->get('file');
        // 得到真实的地址
        $path = public_path() . $filepath;
        // 删除指定的文件
        unlink($path);
        return ['status' => 200, 'msg' => '成功'];
    }

    // export
    public function export()
    {

    }

    // city
    public function city(Request $request)
    {
        $id   = $request->get('id');
        $data = City::where('pid', $id)->get(['id', 'name']);
        return $data;
    }

    //esinit 添加索引
    public function esinit()
    {
        // 得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        // 创建索引
        $params = [
            'index' => 'fang',
            // 类型 _doc
            'body'  => [
                'settings' => [
                    // 分区数  设置好后不能再加
                    'number_of_shards'   => 5,
                    // 副本数  可
                    'number_of_replicas' => 1
                ],
                'mappings' => [
                    '_doc' => [
                        '_source'    => [
                            'enabled' => true
                        ],
                        // 字段 社渚类型
                        'properties' => [
                            'fang_name' => [
                                // 查询的是 你好  ,就必须找到 你好
                                'type' => 'keyword'
                            ],
                            'fang_desn' => [
                                'type'            => 'text',
                                // 文本可以进行中文分词
                                'analyzer'        => 'ik_max_word',
                                'search_analyzer' => 'ik_max_word'
                            ]
                        ]
                    ]
                ]
            ]
        ];
        // 创建索引
        $response = $client->indices()->create($params);
        dump($response);
    }

    // changestu 已租未租信息更改
    public function changestu(Request $request)
    {
        $id  = $request->get('id');
        $stu = $request->get('stu');
        Fang::where('id', $id)->update(['fang_status' => $stu]);
        return ['status' => 200, 'msg' => '房源状态更改成功'];
    }
}
